package com.tanhua.server.interceptor;

import com.tanhua.domain.db.User;
import com.tanhua.server.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("==========请求的路径：==========="+request.getRequestURL());

        log.info("执行拦截器的preHandle()方法，统一身份认证");
        String token = request.getHeader("Authorization");
        if(token == null){
            response.setStatus(401);
            log.info("token为null");
            return false;
        }


        User user = userService.findUserInfoByToken(token);
        if(user == null){
            response.setStatus(401);
            log.info("user为null");
            return false;
        }
        UserHolder.set(user);
        return true;

    }
}
